﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Rooms.Commands.DeleteRoom
{
    public class DeleteRoomCommandHandler : IRequestHandler<DeleteRoomCommand, ErrorOr<Deleted>>
    {
        private readonly IGymsRepository _gymsRepository;
        private readonly IRoomsRepository _roomsRepository;

        public DeleteRoomCommandHandler(IGymsRepository gymsRepository, IRoomsRepository roomsRepository)
        {
            _gymsRepository = gymsRepository;
            _roomsRepository = roomsRepository;
        }

        public async Task<ErrorOr<Deleted>> Handle(DeleteRoomCommand request, CancellationToken cancellationToken)
        {
            var gym = await _gymsRepository.GetByIdAsync(request.GymId);
            if (gym is null)
            {
                return Error.NotFound(description: "没有发现健身房");
            }

            if (!gym.HasRoom(request.RoomId))
            {
                return Error.NotFound(description: "健身房内没有该房房间");
            }

            var room = await _roomsRepository.GetByIdAsync(request.RoomId);
            if (room is null)
            {
                return Error.NotFound(description: "没有找到该房间");
            }

            var removeGymResult = gym.RemoveRoom(room);

            if (removeGymResult.IsError)
            {
                return removeGymResult.Errors;
            }

            await _gymsRepository.UpdateAsync(gym);

            return Result.Deleted;
        }
    }
}
